class TargetDomainDiagnosis:
    def __init__(self, model, feature_extractor):
        self.model = model
        self.feature_extractor = feature_extractor
        
    def diagnose_target_domain(self, target_data):
        """诊断目标域数据"""
        predictions = self.model.predict(target_data)
        return predictions
    
    def visualize_diagnosis_results(self, predictions, true_labels=None):
        """可视化诊断结果"""
        plt.figure(figsize=(15, 10))
        
        # 预测概率分布
        plt.subplot(2, 2, 1)
        plt.imshow(predictions.T, aspect='auto', cmap='viridis')
        plt.colorbar()
        plt.title('Prediction Probability Distribution')
        plt.xlabel('Sample Index')
        plt.ylabel('Class')
        
        # 置信度分布
        plt.subplot(2, 2, 2)
        confidence = np.max(predictions, axis=1)
        plt.hist(confidence, bins=30, alpha=0.7)
        plt.title('Prediction Confidence Distribution')
        plt.xlabel('Confidence')
        plt.ylabel('Count')
        
        if true_labels is not None:
            # 混淆矩阵
            plt.subplot(2, 2, 3)
            pred_labels = np.argmax(predictions, axis=1)
            cm = confusion_matrix(true_labels, pred_labels)
            sns.heatmap(cm, annot=True, fmt='d', cmap='Blues')
            plt.title('Confusion Matrix')
            
            # 分类报告
            plt.subplot(2, 2, 4)
            report = classification_report(true_labels, pred_labels, output_dict=True)
            report_df = pd.DataFrame(report).transpose()
            plt.table(cellText=report_df.values,
                     rowLabels=report_df.index,
                     colLabels=report_df.columns,
                     cellLoc='center',
                     loc='center')
            plt.axis('off')
            plt.title('Classification Report')
        
        plt.tight_layout()
        plt.show()
    
    def generate_diagnosis_report(self, predictions, file_names):
        """生成诊断报告"""
        report_data = []
        for i, (file_name, pred) in enumerate(zip(file_names, predictions)):
            pred_label = np.argmax(pred)
            confidence = np.max(pred)
            report_data.append({
                'file_name': file_name,
                'predicted_label': pred_label,
                'confidence': confidence,
                'probabilities': pred.tolist()
            })
        
        return pd.DataFrame(report_data)

# 目标域诊断示例
diagnosis = TargetDomainDiagnosis(dann_model, feature_extractor)

# 诊断目标域数据
target_predictions = diagnosis.diagnose_target_domain(X_target)

# 可视化结果
diagnosis.visualize_diagnosis_results(target_predictions)

# 生成诊断报告
target_file_names = [f'target_{i}' for i in range(len(X_target))]
diagnosis_report = diagnosis.generate_diagnosis_report(target_predictions, target_file_names)
print(diagnosis_report.head())